package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.ServletUtils;
import com.spzx.product.domain.Brand;
import com.spzx.product.domain.CategoryBrand;
import com.spzx.product.mapper.CategoryBrandMapper;
import com.spzx.product.service.CategoryBrandService;
import com.spzx.product.service.CategoryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper , CategoryBrand> implements CategoryBrandService {
    @Resource
    CategoryService categoryService;
    @Override
    public Page<CategoryBrand> listByCidAndBid(CategoryBrand categoryBrand) {
        //1、获取分页页码、pageSize数据
        Integer pageNum = ServletUtils.getParameterToInt("pageNum" , 1);
        Integer pageSize = ServletUtils.getParameterToInt("pageSize",3);
        Page<CategoryBrand> page = new Page<>(pageNum,pageSize);
        //2、如果携带了查询条件  使用条件分页查询
        //        QueryWrapper<Class<CategoryBrand>> wrapper = Wrappers.query(CategoryBrand.class);
        //        //获取查询条件中的分类和品牌id
        //        Long categoryId = categoryBrand.getCategoryId();
        //        Long brandId = categoryBrand.getBrandId();
        //5、分页查询
        List<CategoryBrand> list = baseMapper.selectByCidAndBid(page , categoryBrand);
        //4、将上面的结果组装返回
        page.setRecords(list);//将查询到的数据列表设置给page对象
        return page;
    }

    @Override
    public CategoryBrand getCategoryBrandById(Long id) {
        CategoryBrand categoryBrand = this.getById(id);
        if(categoryBrand==null){
            return categoryBrand;
        }
        //根据categoryBrand的三级分类id查询 1，2，3级分类id
        categoryBrand.setCategoryIdList(categoryService.selectCategoryIdsByC3Id(categoryBrand.getCategoryId()));
        return categoryBrand;
    }

    @Override
    public boolean checkCategoryBrandIsExists(CategoryBrand categoryBrand) {
        //1、判断新增还是更新
        Long id = categoryBrand.getId()==null?-1L:categoryBrand.getId();
        //2、查询数据判断是否存在
        CategoryBrand selectCategoryBrand = this.getOne(Wrappers.lambdaQuery(CategoryBrand.class)
                .eq(CategoryBrand::getBrandId, categoryBrand.getBrandId())
                .eq(CategoryBrand::getCategoryId, categoryBrand.getCategoryId())
                .last("limit 1"));
        if(selectCategoryBrand!=null &&
                id.longValue() != selectCategoryBrand.getId().longValue()){
            return false;
        }
        return  true;
    }

    @Override
    public int deleteByIds(List<Long> ids) {

        return baseMapper.batchDeleteByIds(ids);
    }

    @Override
    public List<Brand> selectBrandsByC3Id(Long c3id) {


        return baseMapper.selectBrandByC3id(c3id);
    }
}


